//
//  HomeViewController.m
//  Riese
//
//  Created by air on 2019/10/21.
//  Copyright © 2019 wangjinyu. All rights reserved.
//
#define MAS_SHORTHAND_GLOBALS //简化代码，即去掉了mas_前缀
#define MAS_SHORTHAND
#define kMargin 15 //左右边距
#import "HomeViewController.h"
#import "HomeViewCell.h"
#import <QuartzCore/QuartzCore.h>
#import "GBTopScrollMenuView.h"//section的布局
#import "JYJAnimateViewController.h"//个人中心
#import "ViewController.h"
#import <MMAlertView.h>

#import "ConnectViewController.h"
#import "DetailViewController.h"
#import "AddUserViewController.h"
#import "HistoryViewController.h"

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton * btnConnect;
    UIButton * rightBtn;
    UILabel * lab_Con;
}
/** hasClick */

@property (nonatomic, strong) UITableView *tableView1;

@property (nonatomic, assign) BOOL hasClick;
@property (nonatomic, strong) JYJAnimateViewController *vc;//个人中心界面
//section的menu选项
@property (nonatomic, strong) GBTopScrollMenuView *topScrollView;
@property (nonatomic, strong) NSArray *titleArr;  // 要显示的那一行文字
@property (nonatomic) NSInteger currentIndex;

@property (nonatomic, strong) NSMutableArray *idArray; // 所有数据的ID
@property (nonatomic, strong) NSMutableArray *currentIdArray; // 当前选中 tab ID
@property(nonatomic,strong)NSMutableArray * dataArray; // 从数据库中读出的所有数据
@property (nonatomic, strong) NSMutableArray *currentArray; // 当前选中 tab 数据
@property(nonatomic,strong)NSMutableDictionary * dataDic;

@property (nonatomic, strong) FMDatabase *db;

@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    if (!defaults(@"gain")) {
        setDefaults(@"10mm/mV", @"gain");
    }
    if (!defaults(@"speed")) {
        setDefaults(@"25mm/s", @"speed");
    }
    
    lab_Con.text = NSLocalizedString(@"Connect to my device", nil);
    CGSize size = [Common calculateStringSize:lab_Con.text withFont:kMediumFont(15)];
    lab_Con.sd_layout.topEqualToView(btnConnect).bottomEqualToView(btnConnect).leftSpaceToView(btnConnect, (SCREEN_WIDTH - 30 - size.width - 28)/2).widthIs(size.width);
    
    self.titleArr = @[NSLocalizedString(@"Latest", nil), NSLocalizedString(@"Earliest", nil),  NSLocalizedString(@"Normal", nil), NSLocalizedString(@"Abnormal", nil)];
    
    if (!defaults(@"id")) {
        // 创建数据库对象  如果没有选择用户
        NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString * path = [docsdir stringByAppendingPathComponent:@"UserInfo.sqlite"];//将需要创建的串拼接到后面
        self.db = [FMDatabase databaseWithPath:path];
        // 建表
        [self createTable];
    }
    else {
//        //***** 测试iPhone5, 从 longtextData 中读取数据
//        NSString *tempString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"longtextData" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
//        NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithDictionary:[self dictionaryWithJsonString:tempString]];
//        self.dataArray = [NSMutableArray arrayWithArray:@[dic[@"DeviceData"][0], dic[@"DeviceData"][0], dic[@"DeviceData"][0]]];
        
        if (self.currentArray.count == 0) {
            self.currentIndex = 0;
            [self getData];
        }
        else {
            [self getData];
        }
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUser) name:@"updateUser" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:@"updateData" object:nil];
}

- (void)updateData {
    self.currentIndex = 0;
    [self getData];
}

- (void)updateUser {
    if (defaults(@"id")) {
        if ([defaults(@"avatar") length] > 0) {
            NSData *data = defaults(defaults(@"avatar"));
            [rightBtn setBackgroundImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
        }
        else {
            [rightBtn setBackgroundImage:[UIImage imageNamed:@"defaultUser"] forState:UIControlStateNormal];
        }
        
        [self getData];
    }
    else {
        // 创建数据库对象  如果没有选择用户
        NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString * path = [docsdir stringByAppendingPathComponent:@"UserInfo.sqlite"];//将需要创建的串拼接到后面
        self.db = [FMDatabase databaseWithPath:path];
        // 建表
        [self createTable];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromHex(0xF3F3F3);
//    self.navigationItem.title = @"首页";

    self.automaticallyAdjustsScrollViewInsets = NO;
    // 这个方法是为了，不让隐藏状态栏的时候出现view上移
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    // 屏幕边缘pan手势(优先级高于其他手势)
    UIScreenEdgePanGestureRecognizer *leftEdgeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(moveViewWithGesture:)];
    leftEdgeGesture.edges = UIRectEdgeLeft;// 屏幕左侧边缘响应
    [self.view addGestureRecognizer:leftEdgeGesture];
    // 这里是地图处理方式，遵守代理协议，实现代理方法
    leftEdgeGesture.delegate = self;
    
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    self.idArray = [NSMutableArray arrayWithCapacity:0];
//    [self initData];
    [self makeUI];
    
    // Do any additional setup after loading the view.
}

- (void)makeUI{
    [self createNav];
    [self initTableView];
}

#pragma mark - createNav
-(void)createNav{
    UIView * bgViewNav = [[UIView alloc] init];
    bgViewNav.frame = CGRectMake(0, 0, SCREEN_WIDTH, kNavBarAndStatusBarHeight);
    bgViewNav.backgroundColor = UIColorFromHex(0x5CBBC0);
    [self.view addSubview:bgViewNav];
    
    UIImageView * imgHeadNav = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 151)/2, kStatusBarHeight + (kNavHeight - 34)/2, 151, 34)];
    imgHeadNav.image = [UIImage imageNamed:@"home_navTitle"];
    [bgViewNav addSubview:imgHeadNav];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(22, kStatusBarHeight, kNavHeight, kNavHeight);
    [leftBtn setImage:[UIImage imageNamed:@"home_list"] forState:UIControlStateNormal];
    leftBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [leftBtn addTarget:self action:@selector(leftItemClick) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, kNavHeight - 20);
    [bgViewNav addSubview:leftBtn];
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_addLeft"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    
//    if (defaults(@"id")) {
        rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(SCREEN_WIDTH - 45, kStatusBarHeight + (kNavHeight - 30)/2, 30, 30);
        rightBtn.backgroundColor = [UIColor whiteColor];
        [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
        if (defaults(@"id")) {
            if ([defaults(@"avatar") length] > 0) {
                NSData *data = defaults(defaults(@"avatar"));
                [rightBtn setBackgroundImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
            }
            else {
                [rightBtn setBackgroundImage:[UIImage imageNamed:@"defaultUser"] forState:UIControlStateNormal];
            }
        }
        rightBtn.layer.cornerRadius = 15;
        rightBtn.clipsToBounds = YES;
        [bgViewNav addSubview:rightBtn];
//    }
}

- (void)rightBtnClick {
    if (defaults(@"id")) {
//        AddUserViewController *vc = [AddUserViewController new];
//        vc.isEdit = @"1";
//        [self.navigationController pushViewController:vc animated:YES];
        NSData *data = defaults(defaults(@"avatar"));
        HistoryViewController *vc = [HistoryViewController new];
        vc.avatarImg = [UIImage imageWithData:data];
        vc.nickname = defaults(@"nickname");
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark-点击左边 进入个人中心
-(void)leftItemClick{
    //点击了左边
    // 防止重复点击
    if (self.hasClick) return;
    self.hasClick = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.hasClick = NO;
    });
    
    // 展示个人中心
    JYJAnimateViewController *vc = [[JYJAnimateViewController alloc] init];
    self.vc = vc;
    vc.view.backgroundColor = [UIColor clearColor];
    [self addChildViewController:vc];
    [self.view addSubview:vc.view];
}

//#pragma mark - scroll delegate
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    //[self.topScrollView setCurrentIndex:scrollView.contentOffset.x/SCREEN_WIDTH];
//}

-(void)initTableView{
    self.tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
    self.tableView1.backgroundColor = UIColorFromHex(0xF3F3F3);
    self.tableView1.showsVerticalScrollIndicator = NO;
    self.tableView1.delegate = self;
    self.tableView1.dataSource = self;
    self.tableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView1.estimatedRowHeight = 0;
    self.tableView1.estimatedSectionHeaderHeight = 0;
    self.tableView1.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.tableView1];
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    footer.backgroundColor = UIColorFromHex(0xF3F3F3);
    self.tableView1.tableFooterView = footer;
    
    UIView * headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 15 + 45 + 150)];
    headView.backgroundColor = UIColorFromHex(0xF3F3F3);
    self.tableView1.tableHeaderView = headView;
    
    UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH - 30, 150)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [headView addSubview:whiteView];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect: whiteView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10,10)];
    //创建 layer
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = whiteView.bounds;
    //赋值
    maskLayer.path = maskPath.CGPath;
    whiteView.layer.mask = maskLayer;
    
    UIImageView * imgV_Header = [[UIImageView alloc] init];//initWithFrame:CGRectMake(kMargin, 15, SCREEN_WIDTH - kMargin * 2, 150)];
    imgV_Header.image = [UIImage imageNamed:@"home_headerImg"];
    
    [whiteView addSubview:imgV_Header];
    imgV_Header.sd_layout.leftSpaceToView(whiteView, 35).rightSpaceToView(whiteView, 35).topSpaceToView(whiteView, 0).widthIs(whiteView.width - 2 * 35).heightIs(whiteView.height);
    
    //    imgV_Header.image = [self drawLineByImageView:imgV_Header];
//    imgV_Header.layer.borderWidth = 0.5;
//    imgV_Header.layer.borderColor = [UIColor blackColor].CGColor;
    
    btnConnect = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnConnect addTarget:self action:@selector(connectBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:btnConnect];
    
    btnConnect.sd_layout.leftEqualToView(whiteView).topSpaceToView(whiteView, 0).widthIs(whiteView.width).heightIs(45);
    [btnConnect setBackgroundColor:UIColorFromHex(0x5CBBC0)];
    
    UIBezierPath *maskPath_bC = [UIBezierPath bezierPathWithRoundedRect: btnConnect.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10,10)];
    //创建 layer
    CAShapeLayer *maskLayer_bC = [[CAShapeLayer alloc] init];
    maskLayer_bC.frame = whiteView.bounds;
    //赋值
    maskLayer_bC.path = maskPath_bC.CGPath;
    btnConnect.layer.mask = maskLayer_bC;

    lab_Con = [UILabel new];
    [btnConnect addSubview:lab_Con];

    lab_Con.text = NSLocalizedString(@"Connect to my device", nil);
    lab_Con.textColor = [UIColor whiteColor];
    lab_Con.textAlignment = NSTextAlignmentCenter;
    lab_Con.font = kMediumFont(15);
    //
    CGSize size = [Common calculateStringSize:lab_Con.text withFont:kMediumFont(15)];
    lab_Con.sd_layout.topEqualToView(btnConnect).bottomEqualToView(btnConnect).leftSpaceToView(btnConnect, (SCREEN_WIDTH - 30 - size.width - 28)/2).widthIs(size.width);
    
    UIImageView * imgV_rightArrow = [UIImageView new];
    imgV_rightArrow.image = [UIImage imageNamed:@"connect_right"];
    [btnConnect addSubview:imgV_rightArrow];
    imgV_rightArrow.sd_layout.leftSpaceToView(lab_Con, 13).centerYEqualToView(lab_Con).widthIs(15).heightIs(15);
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 60;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * bgView = [UIView new];
    bgView.userInteractionEnabled = YES;
    bgView.backgroundColor = UIColorFromHex(0xF3F3F3);
    bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 60);

    self.topScrollView = [[GBTopScrollMenuView alloc] initWithFrame:CGRectMake(kMargin, 15, SCREEN_WIDTH - 2 * kMargin, 45) showPopViewWithMoreButton:YES];
    self.topScrollView.layer.cornerRadius = 4;
    self.topScrollView.clipsToBounds = YES;
    self.topScrollView.selectedColor = UIColorFromHex(0x5CBBC0);
    self.topScrollView.LineColor = UIColorFromHex(0x5CBBC0);
    self.topScrollView.noSlectedColor = UIColorFromHex(0x666666);
    [bgView addSubview:self.topScrollView];

    self.topScrollView.myTitleArray = self.titleArr;
    [self.topScrollView setCurrentIndex:self.currentIndex];
    
    __weak typeof(self) weakSelf = self;
    self.topScrollView.ItemDidSelectAtIndex = ^(NSInteger index){
        weakSelf.currentIndex = index;
//        [self.topScrollView setCurrentIndex:index];
//        weakSelf.genre = weakSelf.titleIdArr[index];
//        [SVProgressHUD show];
//        [weakSelf getData];
        weakSelf.currentArray = [NSMutableArray arrayWithCapacity:0];
        weakSelf.currentIdArray = [NSMutableArray arrayWithCapacity:0];
        if (index == 2) {
            // normal
            for (int i = (int)self.dataArray.count - 1; i >= 0; i--) {
                NSArray *sortArr = @[
                    weakSelf.dataArray[i][@"sort1"],
                    weakSelf.dataArray[i][@"sort2"],
                    weakSelf.dataArray[i][@"sort3"],
                    weakSelf.dataArray[i][@"sort4"],
                    weakSelf.dataArray[i][@"sort5"],
                    weakSelf.dataArray[i][@"sort6"]
                ];
                NSInteger flag = 0;
                for (int j = 0; j < sortArr.count; j++) {
                    if ([sortArr[j] integerValue] != 0) {
                        flag = 1;
                        break;
                    }
                }
                
                if (flag == 0) {
                    [weakSelf.currentArray addObject:weakSelf.dataArray[i]];
                    [weakSelf.currentIdArray addObject:weakSelf.idArray[i]];
                }
            }
            [weakSelf.tableView1 reloadData];
        }
        else if (index == 3) {
            // abnormal
            for (int i = (int)self.dataArray.count - 1; i >= 0; i--) {
                NSArray *sortArr = @[
                    weakSelf.dataArray[i][@"sort1"],
                    weakSelf.dataArray[i][@"sort2"],
                    weakSelf.dataArray[i][@"sort3"],
                    weakSelf.dataArray[i][@"sort4"],
                    weakSelf.dataArray[i][@"sort5"],
                    weakSelf.dataArray[i][@"sort6"]
                ];
                for (int j = 0; j < sortArr.count; j++) {
                    if ([sortArr[j] integerValue] != 0) {
                        [weakSelf.currentArray addObject:weakSelf.dataArray[i]];
                        [weakSelf.currentIdArray addObject:weakSelf.idArray[i]];
                        break;
                    }
                }
            }
            [weakSelf.tableView1 reloadData];
        }
        else if (index == 0) {
            // latest
            for (int i = (int)self.dataArray.count - 1; i >= 0; i--) {
//                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//                [dateFormatter setDateFormat:@"MM/dd/yyyy"];
//
//                NSDate *nowDate = [NSDate date];
//                NSString *nowDateString = [dateFormatter stringFromDate:nowDate];
//
//                NSString *monthStr =  [NSString stringWithFormat:@"%@", weakSelf.dataArray[i][@"month"]];
//                if (monthStr.length == 1) {
//                    monthStr = [NSString stringWithFormat:@"0%@", monthStr];
//                }
//
//                NSString *dayStr = [NSString stringWithFormat:@"%@", weakSelf.dataArray[i][@"day"]];
//                if (dayStr.length == 1) {
//                    dayStr = [NSString stringWithFormat:@"0%@", dayStr];
//                }
//
//                NSString *timeStr = [NSString stringWithFormat:@"%@/%@/%@", monthStr, dayStr, weakSelf.dataArray[i][@"year"]];
//                if ([nowDateString isEqualToString:timeStr]) {
                    [weakSelf.currentArray addObject:weakSelf.dataArray[i]];
                [weakSelf.currentIdArray addObject:weakSelf.idArray[i]];
//                }
            }
            [weakSelf.tableView1 reloadData];
        }
        else if (index == 1) {
            // earliest
//            for (int i = (int)self.dataArray.count - 1; i >= 0; i--) {
            for (int i = 0; i < self.dataArray.count; i++) {
//                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//                [dateFormatter setDateFormat:@"MM/dd/yyyy"];
//
//                NSDate *nowDate = [NSDate date];
//                NSString *nowDateString = [dateFormatter stringFromDate:nowDate];
//
//                NSString *monthStr =  [NSString stringWithFormat:@"%@", weakSelf.dataArray[i][@"month"]];
//                if (monthStr.length == 1) {
//                    monthStr = [NSString stringWithFormat:@"0%@", monthStr];
//                }
//
//                NSString *dayStr = [NSString stringWithFormat:@"%@", weakSelf.dataArray[i][@"day"]];
//                if (dayStr.length == 1) {
//                    dayStr = [NSString stringWithFormat:@"0%@", dayStr];
//                }
//
//                NSString *timeStr = [NSString stringWithFormat:@"%@/%@/%@", monthStr, dayStr, weakSelf.dataArray[i][@"year"]];
//                if (![nowDateString isEqualToString:timeStr]) {
                    [weakSelf.currentArray addObject:weakSelf.dataArray[i]];
                [weakSelf.currentIdArray addObject:weakSelf.idArray[i]];
//                }
            }
            [weakSelf.tableView1 reloadData];
        }
    };
    return bgView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.currentArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellID = @"homeCell";
    HomeViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[HomeViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.backgroundColor = UIColorFromHex(0xF3F3F3);
    if (self.currentArray.count > 0) {
        cell.dataDic = self.currentArray[indexPath.row];
    }
    
    cell.longPressGesture.view.tag = indexPath.row;
    [cell.longPressGesture addTarget:self action:@selector(cellLongPress:)];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailViewController *vc = [DetailViewController new];
    vc.dataDic = self.currentArray[indexPath.row];
    [self.navigationController pushViewController: vc animated:YES];
}

- (void)moveViewWithGesture:(UIPanGestureRecognizer *)panGes {
    if (panGes.state == UIGestureRecognizerStateEnded) {
        if ([self.childViewControllers containsObject:self.vc]) return;
        [self leftItemClick];
    }
}

#pragma - mark cell长按手势 长按删除
-(void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer{
    if (longRecognizer.state==UIGestureRecognizerStateBegan) {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        //MMAlertView
        NSArray *items = @[MMItemMake(NSLocalizedString(@"cancel", nil), MMItemTypeNormal, nil), MMItemMake(NSLocalizedString(@"sure", nil), MMItemTypeNormal, ^(NSInteger index) {
            [self createDeleteData:longRecognizer.view.tag];
        })];
        
        [[[MMAlertView alloc] initWithTitle:@"" detail:[NSString stringWithFormat:@"\n%@", NSLocalizedString(@"Are you sure to delete?", nil)] items:items] show];
    }
}

#pragma mark - 删除数据(长按删除) FMDB
// 创建表
- (void)createDeleteData:(NSInteger)index {

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"DeviceData"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS DeviceData(ID INTEGER PRIMARY KEY AUTOINCREMENT,'uid' 'text', 'json' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self deleteData:index];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self deleteData:index];
           [self.db close];
           [self getData];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 删除数据
- (void)deleteData:(NSInteger)index {
    NSString *query = [NSString stringWithFormat:@"delete from DeviceData where %@ = %@", @"ID", self.currentIdArray[index]];
    BOOL res = [self.db executeUpdate:query];
    
    if (res) {
        [YJProgressHUD showMessage:NSLocalizedString(@"Delete successfully", nil) inView:self.view];
    }
    else {
        [YJProgressHUD showMessage:NSLocalizedString(@"Delete failed", nil) inView:self.view];
    }
}

#pragma mark - Button Click
- (void)connectBtnClick {
    if (!defaults(@"id")) {
        [YJProgressHUD showMessage:@"请选择用户" inView:self.view];
    }
    else {
        ConnectViewController *vc = [[ConnectViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - FMDB
// 创建表
- (void)createTable{

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"userInfo"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT,'avatar' 'text', 'nickname' 'text', 'sex' 'text','age' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self addUserInfo];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self addUserInfo];
           [self.db close];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 查询数据
- (void)addUserInfo {
//    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM pinyinSimple WHERE alpha like '%%%@%%'",item.dream_keyword];
    FMResultSet *rs = [self.db executeQuery:@"select * from userInfo"];
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    // 遍历结果集
    while ([rs next]) {
        NSDictionary *dic = @{@"id": [rs stringForColumn:@"ID"],@"avatar": [rs stringForColumn:@"avatar"], @"nickname": [rs stringForColumn:@"nickname"], @"sex": [rs stringForColumn:@"sex"], @"age": [rs stringForColumn:@"age"]};
        [arr addObject:dic];
    }
    
    if (arr.count > 0) {
        setDefaults(arr[0][@"id"], @"id");
        setDefaults(arr[0][@"avatar"], @"avatar");
        setDefaults(arr[0][@"nickname"], @"nickname");
        setDefaults(arr[0][@"sex"], @"sex");
        setDefaults(arr[0][@"age"], @"age");
        
        [self getData];
//        rightBtn.hidden = NO;
        if ([defaults(@"avatar") length] > 0) {
            NSData *data = defaults(defaults(@"avatar"));
            [rightBtn setBackgroundImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
        }
        else {
            [rightBtn setBackgroundImage:[UIImage imageNamed:@"defaultUser"] forState:UIControlStateNormal];
        }
    }
    else {
        // 如果没有用户, 增加默认用户
//        rightBtn.hidden = YES;
        // 获取当前年份
        NSDate *senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"yyyy"];
        NSString *thisYearString=[dateformatter stringFromDate:senddate];
        
        NSString *sqlite = [NSString stringWithFormat:@"insert into userInfo(avatar,nickname,sex,age) values ('%@','%@','%@','%@')", @"", @"Riesemed EKG", @"1", thisYearString];
        //2.执行sqlite语句
        //    char *error = NULL;//执行sqlite语句失败的时候,会把失败的原因存储到里面
        BOOL result = [self.db executeUpdate:sqlite];
        if (result) {
            NSLog(@"添加数据成功");
            [self addUserInfo];
        } else {
            NSLog(@"添加数据失败");
            [self addUserInfo];
        }
    }
}

/**
 判断一张表是否已经存在
 @param tablename 表名
 */
- (BOOL)isExistTable:(NSString *)tablename{
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM sqlite_master where type= 'table' and name= '%@';",tablename];
    FMResultSet *rs = [self.db executeQuery:sql];
//    BOOL result = [db executeQuery:sql];
    while ([rs next]) {
        NSInteger count = [rs intForColumnIndex:0];
        if (count == 0) {
            return NO;
        }else {
            return YES;
        }
    }
    return NO;
}

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
    NSLog(@"json解析失败：%@",err);
    return nil;
    }
    return dic;
}

-(NSString *)convertToJsonData:(NSDictionary *)dict {

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

#pragma mark - getData
- (void)getData {
    // 创建数据库对象  如果没有选择用户
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * path = [docsdir stringByAppendingPathComponent:@"DeviceData.sqlite"];//将需要创建的串拼接到后面
    self.db = [FMDatabase databaseWithPath:path];
    // 建表
    [self createDataDevice];
}

#pragma mark - dataDevice FMDB
// 创建表
- (void)createDataDevice{

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"DeviceData"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS DeviceData(ID INTEGER PRIMARY KEY AUTOINCREMENT,'uid' 'text', 'json' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self selectData];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self selectData];
           [self.db close];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 查询数据
- (void)selectData {
    [self.dataArray removeAllObjects];
    [self.idArray removeAllObjects];
    NSString *query = [NSString stringWithFormat:@"select * from DeviceData where uid='%@'", defaults(@"id")];
    FMResultSet *rs = [self.db executeQuery:query];
    // 遍历结果集
    while ([rs next]) {
        NSDictionary *dic = [self dictionaryWithJsonString:[rs stringForColumn:@"json"]];
        [self.dataArray addObject:dic];
        [self.idArray addObject:[rs stringForColumn:@"ID"]];
    }
    
    // latest
    self.currentArray = [NSMutableArray arrayWithCapacity:0];
    self.currentIdArray = [NSMutableArray arrayWithCapacity:0];
    for (int i = (int)self.dataArray.count - 1; i >= 0; i--) {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
//
//        NSDate *nowDate = [NSDate date];
//        NSString *nowDateString = [dateFormatter stringFromDate:nowDate];
//
//        NSString *monthStr =  [NSString stringWithFormat:@"%@", self.dataArray[i][@"month"]];
//        if (monthStr.length == 1) {
//            monthStr = [NSString stringWithFormat:@"0%@", monthStr];
//        }
//
//        NSString *dayStr = [NSString stringWithFormat:@"%@", self.dataArray[i][@"day"]];
//        if (dayStr.length == 1) {
//            dayStr = [NSString stringWithFormat:@"0%@", dayStr];
//        }
//
//        NSString *timeStr = [NSString stringWithFormat:@"%@/%@/%@", monthStr, dayStr, self.dataArray[i][@"year"]];
//        if ([nowDateString isEqualToString:timeStr]) {
            [self.currentArray addObject:self.dataArray[i]];
        [self.currentIdArray addObject:self.idArray[i]];
//        }
    }
    [self.tableView1 reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
